/*
 * This file Copyright (c) 2015. Walle.
 * (http://www.wallellen.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the
 * Walle Agreement (WA) and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or WA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Walle Agreement (WA), this file
 * and the accompanying materials are made available under the
 * terms of the WA which accompanies this distribution, and
 * is available at http://www.wallellen.com/agreement.html
 *
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 */

package com.wallellen.web.easy;

import com.wallellen.core.auth.domain.WebMenu;
import com.wallellen.core.sql.query.DBSort;
import com.wallellen.core.sql.query.DataQuery;
import com.wallellen.core.sql.query.DataQuerys;
import com.wallellen.core.sql.result.DataResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by walle on 12/9/15.
 */
public class EasyUiTreeNode implements Serializable {
    private static final long serialVersionUID = 1L;
    static final Logger log = LoggerFactory.getLogger(EasyUiTreeNode.class);
    private String id;
    private String text;
    private String state = "open";
    private String iconCls;
    private String url;
    private String para;
    private boolean checked;
    private List<EasyUiTreeNode> children = new ArrayList();

    public EasyUiTreeNode(String id, String text) {
        this.id = id;
        this.text = text;
    }

    public EasyUiTreeNode(String id, String text, String state) {
        this.id = id;
        this.text = text;
        if (state != null)
            this.state = state;
    }

    public EasyUiTreeNode(String id, String text, String state, String iconCls) {
        this.id = id;
        this.text = text;
        if (state != null) {
            this.state = state;
        }
        if ((iconCls != null) && (iconCls.trim().length() > 0))
            this.iconCls = iconCls;
    }

    public EasyUiTreeNode(String id, String text, String state, String iconCls, String url, String params) {
        this.id = id;
        this.text = text;
        if (state != null) {
            this.state = state;
        }
        if (url != null) {
            this.url = url;
        }
        if (params != null) {
            this.para = params;
        }
        if ((iconCls != null) && (iconCls.trim().length() > 0))
            this.iconCls = iconCls;
    }

    public EasyUiTreeNode(String id, String text, String state, boolean checked) {
        this.id = id;
        this.text = text;
        if (state != null) {
            this.state = state;
        }
        this.checked = checked;
    }

    public static List<EasyUiTreeNode> addNode_initState(List<EasyUiTreeNode> nodeList, String parentId, String id, String text, String state, String icon, String url, String params) {
        if (nodeList == null) {
            nodeList = new ArrayList();
        }
        EasyUiTreeNode oNode = findNode(nodeList, parentId);
        if (oNode == null) {
            nodeList.add(new EasyUiTreeNode(id, text, state, icon, url, params));
        } else {
            oNode.setState("closed");
        }
        return nodeList;
    }

    public static List<EasyUiTreeNode> addNode_Standard(List<EasyUiTreeNode> nodeList, String parentId, String id, String text, String state) {
        if (nodeList == null) {
            nodeList = new ArrayList();
        }
        EasyUiTreeNode oNode = findNode(nodeList, parentId);
        if (oNode == null)
            nodeList.add(new EasyUiTreeNode(id, text, state));
        else {
            oNode.getChildren().add(new EasyUiTreeNode(id, text, state));
        }
        return nodeList;
    }

    public static List<EasyUiTreeNode> addNode_Standard(List<EasyUiTreeNode> nodeList, String parentId, String id, String text, String state, boolean idcheck) {
        if (nodeList == null) {
            nodeList = new ArrayList();
        }
        EasyUiTreeNode oNode = findNode(nodeList, parentId);
        if (oNode == null) {
            nodeList.add(new EasyUiTreeNode(id, text, state, idcheck));
        } else {
            oNode.getChildren().add(new EasyUiTreeNode(id, text, state, idcheck));

            oNode.setChecked(false);
        }
        return nodeList;
    }

    public static List<EasyUiTreeNode> addNode_Standard(List<EasyUiTreeNode> nodeList, String parentId, String id, String text, String state, boolean idcheck, String icon) {
        if (nodeList == null) {
            nodeList = new ArrayList();
        }
        EasyUiTreeNode oNode = findNode(nodeList, parentId);
        if (oNode == null) {
            EasyUiTreeNode node = new EasyUiTreeNode(id, text, state, idcheck);
            if (icon != null) {
                node.setIconCls(icon);
            }
            nodeList.add(node);
        } else {
            EasyUiTreeNode node = new EasyUiTreeNode(id, text, state, idcheck);
            if (icon != null) {
                node.setIconCls(icon);
            }
            oNode.getChildren().add(node);
            oNode.setChecked(false);
        }
        return nodeList;
    }

    public static List<EasyUiTreeNode> formatAsyncAjaxTree(List<Map<String, Object>> result1, List<Map<String, Object>> result2, String parentIdIndex, String idIndex, String titleIndex, String iconIndex) {
        result1.addAll(result2);
        List treeNodes = new ArrayList();
        try {
            for (Map node : result1) {
                if (node.get(idIndex) != null) {
                    treeNodes = addNode_initState(treeNodes, node.get(parentIdIndex).toString(), node.get(idIndex).toString(), node.get(titleIndex).toString(), null, node.get(iconIndex) != null ? node.get(iconIndex).toString() : null, null, null);
                }
            }

        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return treeNodes;
    }

    public static List<EasyUiTreeNode> formatAsyncAjaxTreeForMenuTree(List<Map<String, Object>> result1, List<Map<String, Object>> result2, String parentIdIndex, String idIndex, String titleIndex, String iconIndex, String urlIndex, String paramsIndex, List<WebMenu> currentUserMenus) {
        result1.addAll(result2);
        List treeNodes = new ArrayList();
        try {
            for (Map node : result1) {
                boolean isShowMenu = false;
                for (WebMenu menu : currentUserMenus) {
                    if (menu.getId().equals(node.get(idIndex))) {
                        isShowMenu = true;
                        break;
                    }
                }
                if (isShowMenu) {
                    treeNodes = addNode_initState(treeNodes, node.get(parentIdIndex).toString(), node.get(idIndex).toString(), node.get(titleIndex).toString(), null, node.get(iconIndex) != null ? node.get(iconIndex).toString() : null, node.get(urlIndex) != null ? node.get(urlIndex).toString() : null, node.get(paramsIndex) != null ? node.get(paramsIndex).toString() : null);
                }

            }

        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return treeNodes;
    }

    public static List<EasyUiTreeNode> formatAjaxTree(List<Map<String, Object>> result1, String parentIdIndex, String idIndex, String titleIndex) {
        List treeNodes = new ArrayList();
        try {
            for (Map node : result1)
                if (node.get(idIndex) != null) {
                    treeNodes = addNode_Standard(treeNodes, node.get(parentIdIndex).toString(), node.get(idIndex).toString(), node.get(titleIndex).toString(), null);
                }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return treeNodes;
    }

    public static List<EasyUiTreeNode> formatAjaxTree(List<Map<String, Object>> result1, String parentIdIndex, String idIndex, String titleIndex, String checkIndex, String iconIndex) {
        List treeNodes = new ArrayList();
        try {
            for (Map node : result1) {
                if (node.get(idIndex) != null) {
                    boolean ischeck = false;
                    if (node.get(checkIndex) == null)
                        ischeck = false;
                    else {
                        ischeck = true;
                    }
                    treeNodes = addNode_Standard(treeNodes, node.get(parentIdIndex).toString(), node.get(idIndex).toString(), node.get(titleIndex).toString(), null, ischeck, node.get(iconIndex) == null ? null : node.get(iconIndex).toString());
                }
            }

        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return treeNodes;
    }

    public static EasyUiTreeNode findNode(List<EasyUiTreeNode> nodeList, String id) {
        for (EasyUiTreeNode node : nodeList) {
            if (node.id.equals(id)) {
                return node;
            }
            EasyUiTreeNode reNode = findNode(node.children, id);
            if (reNode != null) {
                return reNode;
            }
        }

        return null;
    }

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getText() {
        return this.text;
    }

    public String getUrl() {
        return this.url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getPara() {
        return this.para;
    }

    public void setPara(String para) {
        this.para = para;
    }

    public boolean isChecked() {
        return this.checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getState() {
        return this.state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public List<EasyUiTreeNode> getChildren() {
        return this.children;
    }

    public void setChildren(List<EasyUiTreeNode> children) {
        this.children = children;
    }

    public String getIconCls() {
        return this.iconCls;
    }

    public void setIconCls(String iconCls) {
        this.iconCls = iconCls;
    }

    public static DataResult queryTreeNodeTow(String parentId, String SortTitle, String tableTitle, String id_title, String parentId_title, String name_title, String icon_title) {
        return queryTreeNodeTow(parentId, SortTitle, tableTitle, id_title, parentId_title, name_title, icon_title, null);
    }

    public static DataResult queryTreeNodeTow(String parentId, String SortTitle, String tableTitle, String id_title, String parentId_title, String name_title, String icon_title, String userWhere) {
        if ((parentId == null) || (parentId.trim().length() <= 0)) {
            parentId = "NONE";
        }
        DataResult nodeResult = null;
        DBSort sort = new DBSort(new StringBuilder().append("b.").append(SortTitle).toString(), "ASC");
        DataQuery query = DataQuery.getInstance("1", new StringBuilder().append("b.").append(id_title).append(" as ").append(id_title).append(",b.").append(parentId_title).append(" as ").append(parentId_title).append(",b.").append(name_title).append(" as ").append(name_title).append(",b.").append(icon_title).append(" as ").append(icon_title).toString(), new StringBuilder().append(tableTitle).append(" a left join ").append(tableTitle).append(" b on b.").append(parentId_title).append("=a.").append(id_title).toString());

        query.setPagesize(100);
        query.addSort(sort);
        DataQuerys.wipeVirus(parentId);
        if (userWhere != null) {
            query.setSqlRule(new StringBuilder().append("and a.").append(parentId_title).append("='").append(parentId).append("' ").append(userWhere).toString());
        } else {
            query.setSqlRule(new StringBuilder().append("and a.").append(parentId_title).append("='").append(parentId).append("' ").toString());
        }

        try {
            nodeResult = query.search();
        } catch (SQLException e) {
            log.error(e.getMessage());
        }
        return nodeResult;
    }

    public static DataResult queryTreeNodeOne(String parentId, String SortTitle, String tableTitle, String id_title, String parentId_title, String name_title, String icon_title) {
        return queryTreeNodeOne(parentId, SortTitle, tableTitle, id_title, parentId_title, name_title, icon_title, null, null);
    }

    public static DataResult queryTreeNodeOne(String parentId, String SortTitle, String tableTitle, String id_title, String parentId_title, String name_title, String icon_title, String userWhere) {
        return queryTreeNodeOne(parentId, SortTitle, tableTitle, id_title, parentId_title, name_title, icon_title, userWhere, null);
    }

    public static DataResult queryTreeNodeOne(String parentId, String SortTitle, String tableTitle, String id_title, String parentId_title, String name_title, String icon_title, String userWhere, String otherTitles) {
        if ((parentId == null) || (parentId.trim().length() <= 0)) {
            parentId = "NONE";
        }
        DataResult nodeResult = null;
        DBSort sort = new DBSort(new StringBuilder().append("a.").append(SortTitle).toString(), "ASC");
        DataQuery query = DataQuery.getInstance("1", new StringBuilder().append(otherTitles == null ? "" : new StringBuilder().append(otherTitles).append(",").toString()).append(id_title).append(",").append(parentId_title).append(" as ").append(parentId_title).append(",").append(name_title).append(" as ").append(name_title).append(",a.").append(icon_title).append(" as ").append(icon_title).toString(), new StringBuilder().append(tableTitle).append(" a").toString());

        query.setPagesize(100);
        query.addSort(sort);
        DataQuerys.wipeVirus(parentId);
        if (userWhere != null) {
            query.setSqlRule(new StringBuilder().append("and ").append(parentId_title).append("='").append(parentId).append("' ").append(userWhere).toString());
        } else
            query.setSqlRule(new StringBuilder().append("and ").append(parentId_title).append("='").append(parentId).append("'").toString());
        try {
            nodeResult = query.search();
        } catch (SQLException e) {
            log.error(e.getMessage());
        }
        return nodeResult;
    }

    public static List<EasyUiTreeNode> formatTreeNodes(List<Map<String, Object>> resultList, String parentIndex, String idIndex, String titleIndex, String iconIndex) {
        List treeNodes = new ArrayList();
        try {
            for (Map node : resultList) {
                if (node.get(idIndex) != null) {
                    treeNodes = addNode_initState(treeNodes, node.get(parentIndex).toString(), node.get(idIndex).toString(), node.get(titleIndex).toString(), null, node.get(iconIndex) != null ? node.get(iconIndex).toString() : null, null, null);
                }
            }

        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return treeNodes;
    }

    public static DataQuery queryTreeNodeOneAuth(String parentId, String SortTitle, String tableTitle, String id_title, String parentId_title, String name_title, String icon_title, String userWhere, String otherTitles, boolean authFlag) {
        if ((parentId == null) || (parentId.trim().length() <= 0)) {
            parentId = "NONE";
        }
        DataResult nodeResult = null;
        DBSort sort = new DBSort(new StringBuilder().append("a.").append(SortTitle).toString(), "ASC");
        DataQuery query = DataQuery.getInstance("1", new StringBuilder().append(otherTitles == null ? "" : new StringBuilder().append(otherTitles).append(",").toString()).append(id_title).append(",").append(parentId_title).append(" as ").append(parentId_title).append(",").append(name_title).append(" as ").append(name_title).append(",a.").append(icon_title).append(" as ").append(icon_title).toString(), new StringBuilder().append(tableTitle).append(" a").toString());

        query.setPagesize(100);
        query.addSort(sort);
        DataQuerys.wipeVirus(parentId);
        if (authFlag) {
            query.setSqlRule(new StringBuilder().append("and a.").append(parentId_title).append(" is not null").toString());
            query.setSqlRule(new StringBuilder().append("and ").append(parentId_title).append("='").append(parentId).append("'").toString());
        } else if (userWhere != null) {
            query.setSqlRule(new StringBuilder().append("and ").append(parentId_title).append("='").append(parentId).append("' ").append(userWhere).toString());
        } else {
            query.setSqlRule(new StringBuilder().append("and ").append(parentId_title).append("='").append(parentId).append("'").toString());
        }

        return query;
    }

    public static DataQuery queryTreeNodeTowAuth(String parentId, String SortTitle, String tableTitle, String id_title, String parentId_title, String name_title, String icon_title, String userWhere, boolean authFlag) {
        if ((parentId == null) || (parentId.trim().length() <= 0)) {
            parentId = "NONE";
        }
        DataResult nodeResult = null;
        DBSort sort = new DBSort(new StringBuilder().append("b.").append(SortTitle).toString(), "ASC");
        DataQuery query = DataQuery.getInstance("1", new StringBuilder().append("b.").append(id_title).append(" as ").append(id_title).append(",b.").append(parentId_title).append(" as ").append(parentId_title).append(",b.").append(name_title).append(" as ").append(name_title).append(",b.").append(icon_title).append(" as ").append(icon_title).toString(), new StringBuilder().append(tableTitle).append(" a left join ").append(tableTitle).append(" b on b.").append(parentId_title).append("=a.").append(id_title).toString());

        query.setPagesize(100);
        query.addSort(sort);
        DataQuerys.wipeVirus(parentId);
        if (authFlag) {
            query.setSqlRule(new StringBuilder().append("and a.").append(parentId_title).append(" is not null").toString());
            query.setSqlRule(new StringBuilder().append("and a.").append(parentId_title).append("='").append(parentId).append("' ").toString());
        } else if (userWhere != null) {
            query.setSqlRule(new StringBuilder().append("and a.").append(parentId_title).append("='").append(parentId).append("' ").append(userWhere).toString());
        } else {
            query.setSqlRule(new StringBuilder().append("and a.").append(parentId_title).append("='").append(parentId).append("' ").toString());
        }

        return query;
    }
}
